<?php

namespace Mini;

class EventLoop
{
    protected array $tasks = [];
    protected array $timers = [];
    protected bool $running = false;

    public function add(callable $task): void
    {
        $fiber = new \Fiber($task);
        $this->tasks[] = $fiber;
    }

    public function delay(callable $task, int $milliseconds): void
    {
        $time = microtime(true) + $milliseconds / 1000;
        $this->timers[] = [$time, $task];
    }

    public function run(): void
    {
        $this->running = true;

        while ($this->running && (!empty($this->tasks) || !empty($this->timers))) {
            // 处理 Fiber 任务
            foreach ($this->tasks as $i => $fiber) {
                if ($fiber->isStarted()) {
                    if (!$fiber->isTerminated()) {
                        $fiber->resume();
                    } else {
                        unset($this->tasks[$i]);
                    }
                } else {
                    $fiber->start();
                }
            }

            // 处理 Timer
            $now = microtime(true);
            foreach ($this->timers as $i => [$time, $task]) {
                if ($now >= $time) {
                    $this->add($task);
                    unset($this->timers[$i]);
                }
            }

            usleep(1000); // 防止 CPU 占满
        }
    }

    public function stop(): void
    {
        $this->running = false;
    }
}
